
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
layui.use(['tableEdit',"excel","selectInput"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel,
        selectInput = layui.selectInput;

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }

    function getxmselectUser(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            initValue:[user.code],
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }

    let operationList=[];
    let billNoStatusList=[];
    // let taxIncludedList=[];
    let salesmanList=[];
    let deptOperationList=[];
    let deptSalesmanList=[];
    let productDataTypeList=[];
    layer.ready(function () {
        //获取所有公司信息
        $.ajax({
            url: "receivePayment/getCompanyInfo",
            success: function (data) {
                if (data.status == 200) {
                    for (let i in data.data) {
                        //公司名称
                        $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取币种
        $.ajax({
            url: "receivePayment/getCurrencyInfo",
            success: function (data) {
                if (data.status == 200) {
                    for (let i in data.data) {
                        $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //供应商
        $.ajax({
            url: "customer2/getAllInspectUnit",
            success: function (res) {
                if (res.status == 200) {
                    $.each(res.data, function (index, item) {
                        $("#customerCode").append(new Option(item.name, item.code));
                    });
                    form.render('select');
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });

        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();

        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            operationList=getxmselectUser("#operationCode", "operationCode", userTree);
            salesmanList=getxmselectUser("#salesmanCode", "salesmanCode", userTree);
        } else {
            operationList=getxmselectUser("#operationCode", "operationCode", [{name: user.name, value: user.code}])
            salesmanList=getxmselectUser("#salesmanCode", "salesmanCode", [{name: user.name, value: user.code}])
        }
        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptOperationList = getxmselectUser("#deptOperationCode", "deptOperationCode", deptTree);
            deptSalesmanList = getxmselectUser("#deptSalesmanCode", "deptSalesmanCode", deptTree);
        } else {
            deptOperationList = getxmselectUser("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
            deptSalesmanList = getxmselectUser("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
        }

        //单据信息
        let billNoStatus = [
            {name: "草稿箱", value: "1"},
            {name: "待批箱", value: "2,2.1"},
            {name: "已批箱", value: "3"},
            {name: "终止箱", value: "6"},
            {name: "完成箱", value: "4"},
            {name: "垃圾箱", value: "5"}
        ];
        billNoStatusList=getxmselect("#status", "status", billNoStatus);
/*

        //是否含税
        let taxIncluded = [
            {name: "含税出厂价", value: "1"},
            {name: "未税出厂价", value: "2"},
            {name: "含税FOB价", value: "3"},
            {name: "未税FOB价", value: "4"},
        ];
        taxIncludedList=getxmselect("#taxIncluded", "taxIncluded", taxIncluded);
*/

        //采购类型
        let productDataType = [
            {name: "成品", value: "1"},
            {name: "配件", value: "2"},
            {name: "备货", value: "3"},
            {name: "外销", value: "4"},
            {name: "样品", value: "5"},
        ];
        productDataTypeList = getxmselect("#productType", "productType", productDataType);

    });
    form.render();//表单刷新

    let initData = [];
    table.render({
        elem: '#offerselect'
        , data: initData
        , toolbar: '#offertoolbar'
        ,totalRow: true
        , cols: [[
            //以采购产品表为主
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'}
            ,{field: 'purchaseNo', title: '采购合同号',event: "purchaseorderno", sort: true, width: 220}
            , {field: 'purchaseType', title: '采购类型', sort: true, width: 120}
            , {field: 'paymentType', title: '价格条款', sort: true, width: 120}
            , {field: 'earnestRate', width: 120, title: '定金比例', sort: true}
            , {field: 'earnestMoney', width: 120, title: '定金总额', sort: true}
            , {field: 'memo', title: '备注', sort: true, width: 120}
            , {field: 'salesContractNo', title: '外销合同号', sort: true, width: 120}
            , {field: 'supplierName', title: '厂商名称', sort: true, width: 120}
            , {field: 'materialSupplierName', title: '素材供应商', sort: true, width: 120}
            , {field: 'signTime', title: '签约日期', sort: true, width: 120}
            , {field: 'productNo', title: '产品编码', sort: true, width: 120}
            , {field: 'specNo', title: '规格编码', sort: true, width: 220}
            , {field: 'chineseName', title: '产品名称', sort: true, width: 120}
            , {field: 'chineseDesc', width: 120, title: '中文描述' }
            , {field: 'englishDesc', width: 120, title: '英文描述' }
            , {field: 'normExplain', title: '规格说明', sort: true, width: 120}
            , {field: 'amount', title: '产品数量', sort: true, width: 120, totalRow: true}
            , {field: 'currency', title: '币种', sort: true, width: 120}
            , {field: 'price', title: '采购成本', sort: true, width: 120}
            , {field: 'productUnitPrice', title: '产品单价', sort: true, width: 120}

            , {field: 'benchmarkPrice', title: '产品基准价', sort: true, width: 120}
            , {field: 'differentialPrice', title: '差异单价', sort: true, width: 120}
            , {field: 'costDown', title: 'COST DOWN', sort: true, width: 120}
            , {field: 'taxIncluded', title: '是否含税', sort: true, width: 120}

            , {field: 'otherCost', title: '其它费用', sort: true, width: 120}
            , {field: 'memoOfCost', title: '费用备注', sort: true, width: 120}
            , {field: 'priceSubtotal', title: '采购金额', sort: true, width: 120, totalRow: true}
            , {field: 'requestDeliveryDate', title: '要求交货日期', sort: true, width: 120}
            , {field: 'executorName', title: '操作员', sort: true, width: 120}
            , {field: 'salesmanName', title: '业务员', sort: true, width: 120}

            , {field: 'shipmentNo', title: '出运计划单号', sort: true, width: 120}
            , {field: 'planAmount', title: '已计划数量', sort: true, width: 120, totalRow: true}
            , {field: 'unPlanAmount', title: '未计划数量', sort: true, width: 120, totalRow: true}
            , {field: 'billNo', title: '出运明细发票号', sort: true, width: 120}
            , {field: 'productNum', title: '出运数量', sort: true, width: 120, totalRow: true}
            , {field: 'unProductNum', title: '未出运数量', sort: true, width: 120, totalRow: true}
        ]]
        , id: 'offertableid'
        , height: $(document).height() - $('#offerselect').offset().top - 50
        , page: true
        , limit: 300
        , limits: [300, 600, 900]
    });

    table.on('tool(offertable)', function(obj){
        if (obj.event === "purchaseorderno"){
            parent.intab("views/jsp/ExportBusiness/tpl/viewprocurement.jsp?id="+obj.data.id+"&types="+obj.data.purchaseType,"采购明细")
        }
    });

    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }
    form.on('submit(submitform)', function (data) {
        if (isEmpty(operationList.getValue('valueStr')) && isEmpty(deptOperationList.getValue('valueStr')) && isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptSalesmanList.getValue('valueStr'))){
            data.field.operationCode=user.code;
        }
        table.reload('offertableid', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , url: 'carryDetail/statistics/getPurchaseStatisticsOneByPage'
            , where: data.field
        }, 'data');
        return false;
    });

    //客户信息
    let customerInfo = [];
    //客户名称
    let ins = selectInput.render({
        elem: '#customerSelect',
        name: 'customerSelect',
        hasSelectIcon: true,
        placeholder: '请输入名称',
        data: [],
    })
    //监听输入
    ins.on('itemInput(customerSelect)', function (obj) {
        let tempData = [];
        $.ajax({
            url: "basicInformation/getCustomerInfo?info=" + obj.value,
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    customerInfo = res.data.customerInfo;
                    for (let i in customerInfo) {
                        customerInfo[i]["value"] = customerInfo[i].code;
                        tempData.push(customerInfo[i]);
                    }
                }
            }
        })
        ins.addSelect(tempData)
    })

    // 监听select 选择事件
    ins.on('itemSelect(customerSelect)', function (obj) {
        let code = obj.data;
        $("#customerCode").val(code);
    });


    form.on('submit(exportData)', function (queryReq) {
        if (isEmpty(operationList.getValue('valueStr')) && isEmpty(deptOperationList.getValue('valueStr')) && isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptSalesmanList.getValue('valueStr'))){
            queryReq.field.operationCode=user.code;
        }
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"carryDetail/statistics/export/purchase",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 80,
                        'X': 80
                    }, 80);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '采购产品情况一览统计.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });
    document.getElementById('clear').onclick = function(){
        billNoStatusList.setValue([ ]);
        operationList.setValue([ ]);
        // taxIncludedList.setValue([ ]);
        salesmanList.setValue([ ]);
        deptOperationList.setValue([ ]);
        deptSalesmanList.setValue([ ]);
        productDataTypeList.setValue([ ]);
    };
});